package com.sky.wsp.sql.scanner.utils;

import cn.hutool.core.lang.JarClassLoader;
import org.jd.core.v1.ClassFileToJavaSourceDecompiler;

import java.io.File;

/**
 * @author wangshaopeng@talkweb.com.cn
 * @desccription 在此输入描述
 * @date 2024/11/12
 */
public class JdUtil {
    private static ClassFileToJavaSourceDecompiler decompiler = new ClassFileToJavaSourceDecompiler();
    private static JdLoader loader = new JdLoader();
    private JarClassLoader jarClassLoader;

    private JdUtil(JarClassLoader jarClassLoader) {
        this.jarClassLoader = jarClassLoader;
        loader.setJarClassLoader(jarClassLoader);
    }

    public static JdUtil build() {
        return new JdUtil(new JarClassLoader());
    }


    public JdUtil addURL(File classPath) {
        // "D:\\tmp\\cloud-rbac\\WEB-INF\\classes"
        jarClassLoader.addURL(classPath);
        return this;
    }

    public JdUtil addJar(File libPath) {
        // "D:\\soft\\apache-tomcat-8.5.24\\lib"
        // "D:\\tmp\\cloud-rbac\\WEB-INF\\lib"
        jarClassLoader.addJar(libPath);
        return this;
    }

    public String readFile(String fileName) {
        String filePath = fileName.replaceAll("\\\\", "/");
        try {
            if (loader.canLoad(filePath)) {
                JdPrinter printer = new JdPrinter();
                decompiler.decompile(loader, printer, filePath);
                return printer.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
